package com.cqie.hospitalescort.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.hospitalescort.DTO.WeiXinSessionInfoDTO;
import com.cqie.hospitalescort.controller.params.LoginParam;
import com.cqie.hospitalescort.entity.UserInfo;
import com.cqie.hospitalescort.enums.RoleEnum;
import com.cqie.hospitalescort.exception.BusinessException;
import com.cqie.hospitalescort.mapper.UserInfoMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;

@Aspect
@Component
public class WeiXinRegisterAspect {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 微信注册
     *
     * @param joinPoint
     */
    @Before("@annotation(WxUserRegister)")
    @Transactional
    public void enWeiXinUserRegister(JoinPoint joinPoint) {

        //获取方法参数
        Object[] args = joinPoint.getArgs();
        LoginParam param = (LoginParam) args[0];

        if(Objects.isNull(param.getCode())){
            //不是微信登录
            return;
        }

        WeiXinSessionInfoDTO sessionInfo = (WeiXinSessionInfoDTO) args[1];
        if (Objects.isNull(sessionInfo)) {
            throw new BusinessException("微信登录接口[auth.code2Session]无返回！");
        }

        String openid = sessionInfo.getOpenId();
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getOpenid, openid));
        if (Objects.isNull(userInfo)) {
            userInfo = new UserInfo();
            userInfo.setOpenid(openid);
            userInfo.setNickname(param.getNickname());
            userInfo.setGender(param.getGender());
            userInfo.setAvatarurl(param.getAvatarurl());
            userInfo.setTelnum(param.getTelnum());
            userInfo.setRole(RoleEnum.USER.getRole());
            userInfoMapper.insert(userInfo);
        }
    }

    /**
     * 解密电话号码
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     * @throws Exception
     */
    public String decryptPhoneNumber(String sessionKey, String encryptedData, String iv) throws Exception {
        byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] ivBytes = Base64.getDecoder().decode(iv);

        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        byte[] original = cipher.doFinal(encryptedDataBytes);
        String json = new String(original);

        // 解析JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> resultMap = objectMapper.readValue(json, Map.class);
        return (String) resultMap.get("phoneNumber");
    }

}
